<?php
namespace app\api\model;

use think\Exception;
use think\Model;
use think\Cache;
use think\facade\Request;

class UsersModel extends Model{

	protected $table = 'ly_users';

	// 邀请码用户注册
	public function register(){
		$param = input('param.');

		// 新用户信息
		$username	=	(input('post.username')) ? input('post.username') : '';	// 用户名
		$password	=	(input('post.password')) ? input('post.password') : '';	// 密码
		$smscode	=	(input('post.smscode')) ? input('post.smscode') : '';	// 验证码

		$dest			= (input('post.dest')) ? input('post.dest') : 91;	// 国家区号
		$lang			= (input('post.lang')) ? input('post.lang') : 'en';	// 语言类型

        $log = array();

        try{
            if($smscode){
                $cachesmscode	= cache('C_Code_'.$username);
                if(!$cachesmscode){
                    return ['code'=>0,'code_dec'=>config($lang.'.lang')[3]];
                 }

                if($cachesmscode != $smscode){
                    return ['code'=>0,'code_dec'=>config($lang.'.lang')[3]];
                }
            // 	//删除验证码缓存
            // 	cache('C_Code_'.$username, NULL);
             }else{
                $code_rand		= (input('post.code_rand')) ? input('post.code_rand') : '';// 随机码
                $code			= (input('post.code')) ? input('post.code') : '';// 验证码
                $cache_code		= cache('C_Code_'.$code_rand);
                if(!$cache_code || $cache_code != $code || !$code){
                    return ['code'=>0,'code_dec'=>config($lang.'.lang')[3]];
                }
                cache('C_Code_'.$code_rand, NULL);

             }
            model("api/UserLog")->clientlog(0,"注册请求",$log);

            //密码是否一致
            $re_password	=	input('post.re_password/s');	// 密码

            if($password != $re_password or !$password){
                return ['code'=>0,'code_dec'=>config($lang.'.lang')[4]];
            }

            // 检测用户是否已注册
            $countUser = $this->field('id')->where('username', $username)->count();

            if($countUser){
                return ['code'=>0,'code_dec'=>config($lang.'.lang')[5]];
            }

            //  生成邀请码必须唯一
            $is_repeat	= 1;
            $chk_idcode	= 1;
            $idCodearr = $this->column('idcode');
            while($is_repeat == $chk_idcode){	// 防止邀请码重复
                list($msec, $sec) = explode(' ', microtime());
                $msectime	= (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
                $new_idcode		= substr($msectime,-7);		// 邀请码
                if(!in_array($new_idcode,$idCodearr)){
                    $chk_idcode	=	0;
                }
            }
            $recommend		= (input('post.recommend')) ? input('post.recommend') : 0;// 推荐人 邀请码
            if($username==$recommend){
                return ['code'=>0,'code_dec'=>config($lang.'.lang')[6]];
            }

            $qq				= (input('post.qq')) ? input('post.qq') : '';// QQ
            $weixin			= (input('post.weixin')) ? input('post.weixin') : '';// QQ
            $suserinfo		= array();
            if($recommend){
                $where = [
                    ['ly_users.idcode','=',$recommend],
                    ['ly_users.state','=',1],
                ];
                $where2 = [
                    ['ly_users.username','=',$recommend],
                    ['ly_users.state','=',1],
                ];

                $suserinfo = model('Users')->field('ly_users.id,ly_users.vip_level,ly_users.idcode,ly_users.username,ly_users.sid,user_total.balance')->join('user_total','ly_users.id=user_total.uid')->whereOr([$where, $where2])->find();
            }

            $sid	= 0;
            if($suserinfo){
                $sid	=	$suserinfo['id'];
            }else{
                //return ['code'=>0,'code_dec'=>config($lang.'.lang')[6]];
            }

            //邀请码的每日注册人数限制
            $t = time();
            $start = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));
            $end = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t));

            $s_code_reg_num		=	model('Setting')->where('id',1)->value('reg_code_num');
            if($s_code_reg_num>0){
                $code_reg_num 		=	$this->where(array(['recommend','=',$suserinfo['idcode']],['reg_time','>=',$start],['reg_time','<=',$end]))->count();
                if($code_reg_num > $s_code_reg_num){
                    return ['code'=>0,'code_dec'=>config($lang.'.lang')[6]];
                }
            }

            // 用户表注册新用户
            $new_user_data	= [
                'username'    		=> $username,
                'uid'         		=> $new_idcode,
                'password'    		=> auth_code($password,'ENCODE'),
                'phone'       		=> $username,
                'sid'         		=> $sid,//$db_sid,	// 上级id
                'reg_time'    		=> time(),	// 注册时间
                'idcode'      		=> $new_idcode,// 邀请码
                'dest'        		=> $dest,
                'state'      		 => 1,		//
                'qq'		  		=> $qq,
                'weixin'	  		=> $weixin,
                'vip_level'	  		=> 1,		// 普通会员
                'header'	  		=> '/static/head/head_1.png',
                'recommend'	  		=> $suserinfo?$suserinfo['idcode']:'',
                'last_ip'	  		=> request()->ip(),
            ];

            $insert_id = model('Users')->insertGetId($new_user_data);
            if (!$insert_id){
                return ['code'=>0,'code_dec'=>config($lang.'.lang')[7]];
            }

            // 汇总表
            $insertTotalId = model('UserTotal')->insertGetId(array('uid' => $insert_id));
            if (!$insertTotalId) {
                $this->where('id',$insert_id)->delete();
                return ['code'=>0,'code_dec'=>config($lang.'.lang')[7]];
            }

            // 会员加入团队
            $insertTeam	= model('UserTeam')->addUserTeam($insert_id);
            if (!$insertTeam) {
                $this->where('id',$insert_id)->delete();
                model('UserTotal')->where('id',$insertTotalId)->delete();
                return ['code'=>0,'code_dec'=>config($lang.'.lang')[7]];
            }

            //用上级 邀请好友奖励
            /*if($suserinfo){
                //注册奖励
                $regment			= model('Setting')->where('id',1)->value('regment');
                $is_up_to 			= model('UserTotal')->where('uid', $suserinfo['id'])->setInc('balance', $regment);
                if($is_up_to){
                    //加总金额
                    model('UserTotal')->where('uid', $suserinfo['id'])->setInc('total_balance', $regment);
                    // 流水
                    $financial_data_p['uid'] 					= $suserinfo['id'];
                    $financial_data_p['username'] 				= $suserinfo['username'];
                    $financial_data_p['order_number'] 			= 'D'.trading_number();
                    $financial_data_p['trade_number'] 			= 'L'.trading_number();
                    $financial_data_p['trade_type'] 			= 7;
                    $financial_data_p['trade_before_balance']	= $suserinfo['balance'];
                    $financial_data_p['trade_amount'] 			= $regment;
                    $financial_data_p['account_balance'] 		= $suserinfo['balance'] + $regment;
                    $financial_data_p['remarks'] 				= '邀请奖励';
                    $financial_data_p['types'] 					= 1;	// 用户1，商户2
                    model('common/TradeDetails')->tradeDetails($financial_data_p);
                }
            }*/
            //邀请奖励
            return ['code'=>1,'code_dec'=>config($lang.'.lang')[8]];
        }catch (Exception $e){
            $log['异常信息'] = $e->getMessage();
            model("api/UserLog")->clientlog(0,"注册异常",$log);
            return ['code'=>0, 'code_dec'=>'register exception'];
        }

    }


	// 登录系统
	public function login(){

		$param = input('param.');

		//前端到短信验证页面
		$username	=	(input('post.username')) ? input('post.username') : '';	// 语言类型
		$password	=	(input('post.password')) ? input('post.password') : '';	// 语言类型


        $log = array();

		$lang		= (input('post.lang')) ? input('post.lang') : 'en';	// 语言类型
		if(!$username or !$password){
            model("api/UserLog")->clientlog(0,"登录用户名或密码缺失",$log);
			return ['code'=>0,'code_dec'=>config($lang.'.lang')[10]];
		}

		//获取用户信息
		$userinfo = $this->where(array(['username','=',$username]))->find();

		//用户名不存在
		if(!$userinfo){
            model("api/UserLog")->clientlog(0,"登录用户不存在",$log);
			return ['code'=>0,'code_dec'=>config($lang.'.lang')[2]];
		}

        if ($userinfo['state']!=1){
            model("api/UserLog")->clientlog(0,"用户禁止登录",$log);
            return ['code'=>0,'code_dec'=>config($lang.'.lang')[11]];
        }

		//检查密码
		if(auth_code($userinfo['password'],'DECODE') != $password){
			return ['code'=>0,'code_dec'=>config($lang.'.lang')[10]];
		}

        try{
            //用户所在地
            $address = model('Loginlog')->GetIpLookup();
            if (!$address) {
                $address = '';
            }

            model("api/UserLog")->clientlog(0,"尝试登录",$log);

            $type	=	'';
            // 添加登陆日志
            $loginlog = array(
                'uid'			=> $userinfo['id'],
                'username'		=> $userinfo['username'],
                'os'			=> get_os(),
                'browser'		=> get_broswer(),
                'ip'			=> request()->ip(),
                'time'			=> time(),
                'address'		=> $address,
                'type'			=> $type
            );

            $is_v = 1;
            if(request()->ip()==$userinfo['last_ip']){
                $is_v = 0;
            }

            $is_insert_user_loginlog = model('Loginlog')->insert($loginlog);
            if(!$is_insert_user_loginlog){
                return ['code'=>0,'code_dec'=>config($lang.'.lang')[14]];
            }

            //更新用户登录状态
            $is_user_update = $this->where('id',$userinfo['id'])->data(array('last_ip'=>request()->ip(),'last_login'=>time(),'login_error'=>0))->setInc('login_number',1);
            if(!$is_user_update){
                return ['code'=>0,'code_dec'=>config($lang.'.lang')[14]];
            }

            $token = auth_code($userinfo['id'].','.$userinfo['username'],'ENCODE');
            cache('C_token_'.$userinfo['id'],$token,3600*24*14);
            if(!cache('C_token_'.$userinfo['id'])){
                return ['code'=>0,'code_dec'=>config($lang.'.lang')[14]];
            }

            $userTotal = model('UserTotal')->where('uid',$userinfo['id'])->find();

            //返回数据
            $token = cache('C_token_'.$userinfo['id']);
            $data = $this->getuserinfoById($userinfo['id'],$token);
            $data['info']['token']      = $token;
            $data['code']               = 1;
            $data['code_dec']           = config($lang.'.lang')[15];

            return $data;
        }catch (Exception $e){
            $log['异常信息'] = $e->getMessage();
            model("api/UserLog")->clientlog(0,"登录异常",$log);
            return ['code'=>0, 'code_dec'=>'login exception'];
        }

    }

	//收益计算
	public function earnings($param){

		$t = time();
		switch($param['type']){
			case 'today_f_num':
				$start = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));
				$end = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t));
				return model('Task')->where(array(['uid','=',$param['uid']],['add_time','>=',$start],['add_time','<=',$end]))->count();
			break;

			case 'today_j_num':
				$start = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));
				return model('UserDaily')->where(array(['uid','=',$param['uid']],['date','=',$start]))->value('l_t_o_n');
			break;
			case 'today_o_num'://今天完成的次数
				$start = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));
				return model('UserDaily')->where(array(['uid','=',$param['uid']],['date','=',$start]))->value('w_t_o_n');
			break;
			case 'total_profit'://总收益
				return model('UserDaily')->where(array(['uid','=',$param['uid']]))->sum('commission') + model('UserDaily')->where(array(['uid','=',$param['uid']]))->sum('rebate');
			break;
			case 'yesterday_earnings'://昨日收益
				$start 	= mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t))-24*60*60;
				$end 	= mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t))-24*60*60;
				return model('UserDaily')->where(array([['uid','=',$param['uid']],['date','>=',$start],['date','<',$end]]))->sum('commission') + model('UserDaily')->where(array([['uid','=',$param['uid']],['date','>=',$start],['date','<',$end]]))->sum('rebate');

			break;
			case 'today_earnings'://今日收益
				$start 	= mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));
				$end 	= mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t));
				return model('UserDaily')->where(array([['uid','=',$param['uid']],['date','>=',$start],['date','<=',$end]]))->sum('commission') + model('UserDaily')->where(array([['uid','=',$param['uid']],['date','>=',$start],['date','<=',$end]]))->sum('rebate');
			break;
			case 'week_earnings'://本周收益

				$today = date('Y-m-d H:i:s',mktime(0,0,0,date('m'),date('d'),date('Y')));
				$today_end = date('Y-m-d H:i:s',mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1);
				$w = date('w',strtotime($today));
				$start 	= mktime(0,0,0,date('m'),date('d')-$w+1,date('Y'));
				$end 	= mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t));
				return model('UserDaily')->where(array([['uid','=',$param['uid']],['date','>=',$start],['date','<=',$end]]))->sum('commission') + model('UserDaily')->where(array([['uid','=',$param['uid']],['date','>=',$start],['date','<=',$end]]))->sum('rebate');
			break;
			case 'month_earnings'://本月

				$now=time();

				$end	=	strtotime('+1 month');
				$start	=	mktime(0,0,0,date('m',$now),1,date('Y',$now));//当前月开始时间

				$end	=	mktime(0,0,0,date('m',$end),1,date('Y',$end))-1;//当前月结束时间

				return model('UserDaily')->where(array([['uid','=',$param['uid']],['date','>=',$start],['date','<=',$end]]))->sum('commission') + model('UserDaily')->where(array([['uid','=',$param['uid']],['date','>=',$start],['date','<=',$end]]))->sum('rebate');
			break;

			case 'last_month_earnings':

				$start 				= mktime(0,0,0,date('m')-1,str_pad(1,2,0,STR_PAD_LEFT),date('Y'));

				$last_month_days 	= date('t',strtotime(date('Y').'-'.(date('m')-1).'-'.str_pad(1,2,0,STR_PAD_LEFT)));

				$end 		= mktime(0,0,0,date('m')-1,$last_month_days,date('Y'))+24*60*60;

				return model('UserDaily')->where(array([['uid','=',$param['uid']],['date','>=',$start],['date','<=',$end]]))->sum('commission') + model('UserDaily')->where(array([['uid','=',$param['uid']],['date','>=',$start],['date','<',$end]]))->sum('rebate');
			break;

		}

		return 0;

	}
	/*
		获取统计信息
	*/
	public function getStatisticsInfo(){
		$param		= input('param.');
		$token		= $param['token'];
		$userArr	= explode(',',auth_code($token,'DECODE'));
		$uid		= $userArr[0];

		$lang		= (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		$userinfo	= $this->where('id', $uid)->find();
		if(!$userinfo){
			$data['code'] = 2;
			if($lang=='cn')	$data['code_dec'] = '用户名不存在';
			else $data['code_dec'] 	= 'Username does not exist!';
			return $data;
		}

		$UserGrade	= model('UserGrade')->where('grade', $userinfo['vip_level'])->find();
		if(!$UserGrade){
			$data['code'] = 0;
			if($lang=='cn')	$data['code_dec'] = '用户等级不存在';
			else $data['code_dec'] 	= 'User level does not exist!';
			return $data;
		}

		$data	= [];

		$data['info']['yesterday_earnings']  			= round($this->earnings(array('type'=>'yesterday_earnings','uid'=>$userinfo['id'])),3);//昨日收益
		$data['info']['today_earnings']  				= round($this->earnings(array('type'=>'today_earnings','uid'=>$userinfo['id'])),3);//今日收益
		$data['info']['week_earnings']  				= round($this->earnings(array('type'=>'week_earnings','uid'=>$userinfo['id'])),3);//本周收益
		$data['info']['month_earnings']  				= round($this->earnings(array('type'=>'month_earnings','uid'=>$userinfo['id'])),3);//本月收益
		$data['info']['last_month_earnings']  			= round($this->earnings(array('type'=>'last_month_earnings','uid'=>$userinfo['id'])),3);//上月收益
		$data['info']['today_o_num']  					= $this->earnings(array('type'=>'today_o_num','uid'=>$userinfo['id']));//今日完成
		$data['info']['today_s_o_num']  				= $UserGrade['number'] - $this->earnings(array('type'=>'today_j_num','uid'=>$userinfo['id']));//今日剩余任务(单)
		$data['info']['total_profit']  					= round($this->earnings(array('type'=>'total_profit','uid'=>$userinfo['id'])),3);//总收益

		$data['code']	= 1;
		return $data;
	}
	//验证短信接口
	public function checkSlogin(){
		//登录成功后，短信验证
		$param			= input('param.');
		$token			= $param['token'];
		$userArr		= explode(',',auth_code($token,'DECODE'));//uid,username
		$uid			= $userArr[0];	//uid
		$username     	= $userArr[1];	//username
		$code 			= $param['code']; //验证码
		$lang			= (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		//手机号 密码 验证码
		$code =	$param['code'];

		$cache_code	= cache('C_Code_'.$username);

		if(empty($code) or $code != $cache_code){
			return ['code'=>0,'code_dec'=>config($lang.'.lang')[16]];
		}

		$this->where('id',$uid)->data(array('last_login'=>time(),'last_ip'=>request()->ip(),'login_error'=>0))->setInc('login_number',1);
		cache('C_Code_'.$username,NULL);

		return ['code'=>1,'code_dec'=>config($lang.'.lang')[17]];
	}


    public function checkuserinfo(){
        $param			= input('param.');
        $token = $param['token'];
        $userArr		= explode(',',auth_code($token,'DECODE'));//uid,username
        $uid			= $userArr[0];//uid

        $user	= $this->where('id',$uid)->find();

        //支付密码验证
        if (isset($param['payword'])){
            $db_pw	= $user['fund_password'];
            $db_pw	= auth_code($db_pw, 'DECODE');
            if($param['payword'] != $db_pw){
                return ['code' => 0, 'code_dec' => '密码不正确'];
            }
            return ['code' => 1];
        }
    }

	// 找回密码————验证短信接口
	public function checkSmsResetPw(){
		$phone	= input('post.phone/d');	// 手机号
		$code	= input('post.code/d');		// 验证码
		$lang	= (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		$cache_code = cache('C_Code_'.$phone);
		cache('C_CHKSMSLOG_'.$phone,NULL);	// 初始化

		if($code != $cache_code || !$code){
			return ['code'=>0,'code_dec'=>config($lang.'.lang')[3]];
		}

		cache('C_CHKSMSLOG_'.$phone,$phone,600);

		$data['code'] 		= 1;
		$data['code_dec'] 	= config($lang.'.lang')[17];
		$data['phone'] 		= $phone;
		return $data;
	}


	/*  找回密码————设置新密码  */
	public function resetPassword(){
		$phone			= input('post.username/s');
		$password		= input('post.password/s');
		$re_password	= input('post.re_password/s');
		$lang			= (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		// 验证密码是否一致
		if(empty($password) || empty($re_password) || $password != $re_password){
			return ['code'=>0,'code_dec'=>config($lang.'.lang')[18]];
		}

		// 验证手机号
//		$cache_phone	= cache('C_CHKSMSLOG_'.$phone);
//		if(empty($phone) || empty($cache_phone) || $phone != $cache_phone){
//			return ['code'=>0,'code_dec'=>config($lang.'.lang')[3]];
//		}

		// 验证用户
		$uid	= $this->where('username',$phone)->value('id');

		if(empty($uid)){
			return ['code'=>0,'code_dec'=>config($lang.'.lang')[2]];
		}

		// 更新重置密码
		$update_ok	= $this->where('id',$uid)->update(['password'=>auth_code($password,'ENCODE')]);

		if(!$update_ok){
			return ['code'=>0,'code_dec'=>config($lang.'.lang')[20]];
		}

		return ['code'=>1,'code_dec'=>config($lang.'.lang')[21]];
	}


	/*  修改密码  */
	public function changePassword(){
		$token			= input('post.token/s');
		$userArr		= explode(',',auth_code($token,'DECODE'));
		$uid			= $userArr[0];
		$username     	= $userArr[1];
		$lang			= (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		$old_password		= input('post.password/s');
		$new_password		= input('post.n_password/s');
		$new_re_password	= input('post.r_password/s');

		// 验证密码是否一致
		if(empty($new_password) || empty($new_re_password) || $new_password != $new_re_password){
			return ['code'=>0,'code_dec'=>config($lang.'.lang')[18]];
		}

		// 验证用户，并获取原密码
		$o_password	= $this->where(['id'=>$uid,'username'=>$username])->value('password');

		if(empty($o_password)){
			return ['code'=>0,'code_dec'=>config($lang.'.lang')[2]];
		}

		// 比较原密码是否一致
		$o_password	= auth_code($o_password,'DECODE');

		if($old_password != $o_password){
			return ['code'=>0,'code_dec'=>config($lang.'.lang')[22]];
		}

		// 更新密码
		$update_ok	= $this->where('id',$uid)->update(['password'=>auth_code($new_password,'ENCODE')]);

		if(!$update_ok){
			return ['code'=>0,'code_dec'=>config($lang.'.lang')[23]];
		}

		return ['code'=>1,'code_dec'=>config($lang.'.lang')[24]];
	}

    public function getuserinfo()
    {
        $param = input('param.');
        $token = $param['token'];
        $userArr		= explode(',',auth_code($token,'DECODE'));//uid,username
        $uid			= $userArr[0];//uid

        return $this->getuserinfoById($uid,$token);
    }

	//获取用户信息
	public function getuserinfoById($uid,$token){
		$lang			= (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		$userinfo = $this->field('ly_user_total.*,ly_users.*')->join('ly_user_total','ly_users.id=ly_user_total.uid')->where(array('ly_users.id'=>$uid))->findOrEmpty();
		if (!$userinfo) return ['code'=>0];



		$data['code']                                = 1;

		$data['token']                               = $token;

		$data['info']['userid']                      = $userinfo['id'];

		$data['info']['uid']                         = $userinfo['uid'];
		$data['info']['username']                    = $userinfo['username'];
		$data['info']['nickname']                    = $userinfo['nickname'];

        $fund_pwd_len = 0;
        if ($userinfo['fund_password']&&strlen($userinfo['fund_password'])>0){
            $fund_pwd_len = $userinfo['fund_password'];
        }
        $data['info']['fund_pwd_len']                = $fund_pwd_len;

		$data['info']['balance']                     = $userinfo['balance'];		//余额

		$data['info']['user_type']               = $userinfo['user_type'];

		//$data['info']['realname']                    = $userinfo['realname'];

		//$data['info']['state']                       = $userinfo['state'];

		$data['info']['dest']                        = $userinfo['dest'];//国家区号

		$data['info']['phone']                       = $userinfo['phone'];//手机号
		// $data['info']['facebook']                    = $userinfo['facebook'];//手机号
		// $data['info']['volcanic']                    = $userinfo['volcanic'];//手机号
		// $data['info']['photo_wall']                  = $userinfo['photo_wall'];//手机号
		// $data['info']['chingari']                    = $userinfo['chingari'];//手机号

		$is_realname                                 =	0;

		if($userinfo['realname'])		$is_realname =	1;

		$data['info']['is_realname']                 = $is_realname;		//是否实名

		$data['info']['vip_level']                   = $userinfo['vip_level'];

        $bankCard = db('user_bank')->where('uid',$uid)->where('status',1)->find();

        $data['info']['bankInfo'] = $bankCard;

		$data['info']['sid']            = $userinfo['sid'];//直属上级id

		$data['info']['credit']         = $userinfo['credit'];//信用

		$data['info']['idcode']         = $userinfo['idcode'];//邀请码

		// $data['info']['qq']             = $userinfo['qq'];//邀请码
		// $data['info']['weixin']         = $userinfo['weixin'];//邀请码
		// $data['info']['douyin']         = $userinfo['douyin'];//邀请码
		// $data['info']['kuaishou']       = $userinfo['kuaishou'];//邀请码
		// $data['info']['alipay']         = $userinfo['alipay'];//邀请码
		// $data['info']['alipay_name']    = $userinfo['alipay_name'];//邀请码
		// $data['info']['is_housekeeper'] = $userinfo['is_housekeeper'];//云管家

		$data['info']['header']=$userinfo['header']?($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$userinfo['header']):'';

		$data['info']['nft_number']=db('nft')->where(['uid'=>$uid,'status'=>1,'state'=>1,'is_move'=>0])->count();//nft数量
		$data['info']['collect_number']=db('users_task_collect')->where(['uid'=>$uid])->count();//收藏的数量
        $hold_goods_amount = db('users_goods')->where(['uid'=>$uid,'status'=>1])->sum('reward_price*available_number');//持仓
        $hold_goods_count = db('users_goods')->where(['uid'=>$uid,'status'=>1])->sum('available_number');//持仓
        $hold_roy_amount = db('users_roy')->where(['uid'=>$uid,'status'=>1])->sum('number');//
        $hold_roy_count = db('users_roy')->where(['uid'=>$uid,'status'=>1])->sum('number');//
        $data['info']['hold_amount']= $hold_goods_amount+$hold_roy_amount;
        $data['info']['hold_count']= $hold_goods_count+$hold_roy_count;
        $data['info']['debris_number']= $hold_goods_count+$hold_roy_count;
        $data['info']['hold_cost']=db('users_goods')->where(['uid'=>$uid,'status'=>1])->sum('release_price*available_number');//成本
        $data['info']['pledge_amount']=db('users_goods')->where(['uid'=>$uid,'status'=>1])->sum('reward_price*pledge_number');//质押
        $data['info']['pledge_income']= 0;

        $roys = db('users_roy')->where('uid',$uid)->find();
        $data['info']['roys']= 0;
        if ($roys){
            $data['info']['roys'] = $roys['number'];
        }


		if($userinfo['fund_password']){
			$data['info']['is_fund_password']				=	1;
		}else{
			$data['info']['is_fund_password']				=	0;
		}

		$data['info']['susername']			=	'';
		if($userinfo['sid']){//获取上级的用户名 且开启自动加好友的
			$data['info']['susername']		=	$this->where(array(['id','=',$userinfo['sid']],['state','=',1],['is_auto_f','=',1]))->value('username');
		}

		return $data;
	}

	//激活
	public function activationUser(){

		$param			= input('param.');
		$token			= $param['token'];
		$userArr		= explode(',',auth_code($token,'DECODE'));
		$uid			= $userArr[0];
		$username     	= $userArr[1];
		$lang			= (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		$bankcount		=	model('UserBank')->where('uid',$uid)->count();//绑定银行卡数量

		if(!$bankcount){
			return ['code'=>4,'code_dec'=>config($lang.'.lang')[25]];
		}

		//用户余额
		$userTotaldata	= 	model('UserTotal')->where('uid' , $uid)->find();
		$usersbalance 	=	$userTotaldata['balance'];

		//激活金额
		$activation_balance		= model('Setting')->where('id',1)->value('activation_balance');
		//如果是0 直接激活
		if($activation_balance==0){
			$this->where('id' , $uid)->update(array('state'=>1,'at_time'=>time()));
		}

		if($usersbalance < $activation_balance){
			return ['code'=>7,'code_dec'=>config($lang.'.lang')[26]];
		}

		//扣钱激活

		$is_updata_user = model('UserTotal')->where('uid' , $uid)->Dec('balance', $activation_balance)->update();

		if (!$is_updata_user) {
			return ['code'=>0,'code_dec'=>config($lang.'.lang')[27]];
		}

		//更新用户状态
		$is_u = $this->where('id' , $uid)->update(array('state'=>1,'at_time'=>time()));
		if(!$is_u){
			//把钱还回去
			model('UserTotal')->where('uid' , $uid)->Inc('balance', $activation_balance)->update();
			return ['code'=>0,'code_dec'=>config($lang.'.lang')[27]];
		}

		$order_number = 'D'.trading_number();
		$trade_number = 'L'.trading_number();

		//流水
		$financial_data['uid'] 						= $uid;
		$financial_data['username'] 				= $username;
		$financial_data['order_number'] 			= $order_number;
		$financial_data['trade_number'] 			= $trade_number;
		$financial_data['trade_type'] 				= 2;
		$financial_data['account_frozen_balance']	= $userTotaldata['frozen_balance'];
		$financial_data['trade_before_balance']		= $usersbalance;
		$financial_data['trade_amount'] 			= $activation_balance;
		$financial_data['account_balance'] 			= $usersbalance - $activation_balance;
		$financial_data['remarks'] 					= '激活账号';
		$financial_data['types'] 					= 1;
		$is_f = model('TradeDetails')->tradeDetails($financial_data);
		if(!$is_f){
			$this->where('id' , $uid)->update(array('state'=>2));
			//把钱还回去
			model('UserTotal')->where('uid' , $uid)->Inc('balance', $activation_balance)->update();

			return ['code'=>0,'code_dec'=>config($lang.'.lang')[27]];
		}
		return ['code'=>1,'code_dec'=>config($lang.'.lang')[28]];
	}


	//设置用户信息
	public function setuserinfo(){
		$param			= input('param.');
		$token			= $param['token'];
		$userArr		= explode(',',auth_code($token,'DECODE'));
		$uid			= $userArr[0];
		$lang			= (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		unset($param['token']);
		unset($param['lang']);
		if(!$param){
			return ['code'=>0,'code_dec'=>config($lang.'.lang')[29]];
		}
		$filedarry = array('vip_level','sid','user_type','state','withdraws_state');
		foreach ($param as $pk => $pv) {
			if (in_array($pk,$filedarry)) {
				return ['code'=>0,'code_dec'=>config($lang.'.lang')[29]];
			}
		}
		// 获取用户信息
		$chk_user	= $this->where('id',$uid)->count();
		if(!$chk_user)	return ['code' => 0, 'code_dec' => '用户不存在'];

        //修改头像:
        if (isset($param['header'])) {
            $header = '';
            $imgcontent = $param['header'];
            $screenFile = base64_image_content($imgcontent, "./upload/image");
            if ($screenFile) {
                $header = $screenFile;
            }
            if (strlen($header)>0){
                $param['header'] = $header;
            }else{
                unset($param['header']);
            }
        }

		/* 更改支付密码——开始 */
		$o_payword		= input('post.o_payword/s');	//旧支付密码
		$n_payword		= input('post.n_payword/s');	//新支付密码
		$r_payword		= input('post.r_payword/s');	//确认密码

		// 设置支付密码
		if(!$o_payword && $n_payword && $r_payword){		// 如果o_payword不为空，则修改密码

			if(empty($n_payword) || empty($r_payword)) return ['code'=>0,'code_dec'=>config($lang.'.lang')[30]];// 检测新密码不能为空

			if($n_payword != $r_payword) return ['code'=>0,'code_dec'=>config($lang.'.lang')[31]];				// 检测新支付密码不一致

			// 检测旧密码是否为空，为空则设置密码
			$db_pw	= $this->where('id', $uid)->value('fund_password');
			if(!$db_pw){
				$is_ok	= $this->where('id', $uid)->update(['fund_password'=>auth_code($n_payword, 'ENCODE')]);
				if($is_ok) return ['code'=>1,'code_dec'=>config($lang.'.lang')[32]];
			}else{
				return ['code'=>0,'code_dec'=>config($lang.'.lang')[33]];
			}
		}
		// 修改支付密码
		if($o_payword && $n_payword && $r_payword){		// 如果支付不为null，修改密码
			if(empty($n_payword) || empty($r_payword)) return ['code'=>0,'code_dec'=>config($lang.'.lang')[30]];	// 检测新密码不能为空

			if($n_payword != $r_payword) return ['code'=>0,'code_dec'=>config($lang.'.lang')[31]];				// 检测新支付密码不一致

			// 检测旧密码是否输入正确
			$db_pw	= $this->where('id', $uid)->value('fund_password');
			$db_pw	= auth_code($db_pw, 'DECODE');
			if($o_payword != $db_pw){
				return ['code'=>0,'code_dec'=>config($lang.'.lang')[34]];// 检测旧密码是否与数据表里的一致，不一致，则返回错误代码
			}else{	// 旧密码正确，则更新为新密码
				$is_ok	= $this->where('id', $uid)->update(['fund_password'=>auth_code($n_payword, 'ENCODE')]);
				if($is_ok) return ['code'=>1,'code_dec'=>config($lang.'.lang')[35]];
			}
		}
		/* 更改支付密码——结束 */

		/* 认证实名——开始 */
		if(isset($param['realname']) && empty($param['realname'])){		// 实名认证不能未传数据
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[37]];
		}
		if(isset($param['realname']) && !empty($param['realname'])){		// 实名认证，不允许曾经已认证过
			$db_realname	= $this->where('id', $uid)->value('realname');
			if($db_realname){
				return ['code'=>0, 'code_dec'=>config($lang.'.lang')[37]];
			}
			$uservip    = $this->where('id', $uid)->value('vip_level');
			if ($uservip == 1) {//普通会员实名不能重复
				$realnamecount  = $this->where('vip_level',1)->where('realname',$param['realname'])->count();
				 if ($realnamecount > 0) {
					 return ['code'=>0, 'code_dec'=>config($lang.'.lang')[37]];
				 }
			}
		}

		/* 认证实名——结束 */

		/* 更改登录密码——开始 */
		$o_password	= input('post.o_password/s');	//旧登录密码
		$n_password	= input('post.n_password/s');	//新登录密码
		$r_password	= input('post.r_password/s');	//确认密码

		if($o_password && $n_password && $r_password){
			if(empty($n_password) || empty($r_password)) return ['code'=>0, 'code_dec'=>config($lang.'.lang')[30]];	// 检测新密码不能为空

			if($n_password != $r_password) return ['code'=>0, 'code_dec'=>config($lang.'.lang')[4]];				// 检测新密码不一致

			// 检测旧密码是否输入正确
			$db_pw	= $this->where('id', $uid)->value('password');
			$db_pw	= auth_code($db_pw, 'DECODE');
			if($o_password != $db_pw){
				return ['code'=>0, 'code_dec'=>config($lang.'.lang')[36]];// 检测旧密码是否与数据表里的一致，不一致，则返回错误代码
			}else{	// 旧密码正确，则更新为新密码
				$is_ok = $this->where('id', $uid)->update(['password'=>auth_code($n_password, 'ENCODE')]);
				if($is_ok){
					return ['code'=>1, 'code_dec'=>config($lang.'.lang')[24]];
				}
				return ['code'=>0, 'code_dec'=>config($lang.'.lang')[23]];
			}
		}
		/* 更改登录密码——结束 */

		// 存储相应的数据到表中
		$aff = $this->allowField(true)->save($param, ['id' => $uid]);
		if (!$aff){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
		}

		return ['code'=>1, 'code_dec'=>config($lang.'.lang')[42]];

	}


	//退出登陆
	public function logout(){
		$token		= input('post.token/s');
		$userArr	= explode(',',auth_code($token,'DECODE'));
		$uid		= $userArr[0];
		$lang		= (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		cache('C_token_'.$uid,NULL);	//删除登录缓存

		return ['code'=>1, 'code_dec'=>config($lang.'.lang')[43]];
	}


	/**
	 * [userSid 获取所有上级]
	 * @param  [type] $id     [description]
	 * @param  string $select [description]
	 * @param  array  $array  [description]
	 * @return [type]         [description]
	 */
	public function userSid($id,$select='id,sid',$array=array()){
		$user_info =  $this->where('id',$id)->field($select)->find();	//查询上级

		$array[] = $user_info['id'];

		if($user_info['sid']){
			$array = $this->userSid($user_info['sid'],$select,$array);
		}

		return $array;
	}



	//领取佣金
	public function receiveCommission(){
		//佣金 ls=流水 fd=返点 rj=佣金
		$commissionData =  array(
			array('ls'=>2,'fd'=>5,'rj'=>10),
			array('ls'=>5,'fd'=>10,'rj'=>50),
			array('ls'=>10,'fd'=>15,'rj'=>150),
			array('ls'=>20,'fd'=>20,'rj'=>400),
			array('ls'=>40,'fd'=>25,'rj'=>1000),
			array('ls'=>80,'fd'=>30,'rj'=>2400),
			array('ls'=>140,'fd'=>40,'rj'=>5600),
			array('ls'=>230,'fd'=>50,'rj'=>11500),
			array('ls'=>350,'fd'=>60,'rj'=>21000),
			array('ls'=>550,'fd'=>70,'rj'=>38500),
			array('ls'=>800,'fd'=>80,'rj'=>64000),
		);
		$param			=	input('param.');
		$token			=	$param['token'];
		$userArr		=	explode(',',auth_code($token,'DECODE'));
		$uid			=	$userArr[0];
		$username     	=	$userArr[1];




	}

	//我的团队
	public function userTeamTotal(){
		$param			=	input('param.');
		$token			=	$param['token'];
		$userArr		=	explode(',',auth_code($token,'DECODE'));
		$uid			=	$userArr[0];
		$lang			= (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		// 今日事件
		$today = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
		$todayEnd = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
		// 今日团队业绩
		$dateTeamTotal = model('UserDaily')->join('user_team', 'ly_user_daily.uid = user_team.team')->where(array(['user_team.uid','=',$uid],['ly_user_daily.date','>=',$today],['ly_user_daily.date','<=',$todayEnd]))->sum('order');
		// 团队成员信息
		$teamUserInfo = $this->field('ly_users.reg_time,state,at_time')->join('user_team', 'ly_users.id = user_team.team')->where('user_team.uid', $uid)->select()->toArray();
		if(!count($teamUserInfo)){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[44]];
		}
		// 团队激活人数，单位：万
		$TeamActivationNumber     = 0;
		// 今日新增
		$DateTeamNumber           = 0;
		// 今日激活
		$DateTeamActivationNumber = 0;
		// 提取
		foreach ($teamUserInfo as $key => $value) {
			if ($value['state'] == 1) $TeamActivationNumber++;
			if ($value['reg_time'] >= $today && $value['reg_time'] <= $todayEnd) $DateTeamNumber++;
			if ($value['at_time'] >= $today && $value['at_time'] <= $todayEnd) $DateTeamActivationNumber++;
		}

		$data = array(
			'DateTeamTotal'					=>	$dateTeamTotal,
			'TeamNumber'					=>	count($teamUserInfo),
			'TeamActivationNumber'			=>	$TeamActivationNumber,
			'DateTeamNumber'				=>	$DateTeamNumber,
			'DateTeamActivationNumber'		=>	$DateTeamActivationNumber,
		);
		return $data;
	}


	//我的下级
	public function userTeamlist(){
		$param    =	input('param.');
		$userArr  =	explode(',',auth_code($param['token'],'DECODE'));
		$uid      =	$userArr[0];
		$lang	  = (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		// 初始化查询条件
		$where[] = ['sid','=',$uid];
		// 搜索用户名
		if (isset($param['username']) && $param['username']) {
			$where[] = ['username','=',trim($param['username'])];
		}
		// 搜索状态
		if (isset($param['is_at']) && $param['is_at']) {
			$where[] = ['state','=',$param['is_at']];
		}
		// 总记录数
		$count       = $this->where($where)->count();
		if (!$count) return ['code'=>0, 'code_dec'=>config($lang.'.lang')[45]];
		// 每页显示记录
		$pageSize    = (isset($param['page_size']) and $param['page_size']) ? $param['page_size'] : 10;
		// 当前的页,还应该处理非数字的情况
		$pageNo      = (isset($param['page_no']) and $param['page_no']) ? $param['page_no'] : 1;
		// 总页数
		$pageTotal   = ceil($count / $pageSize);//当前页数大于最后页数，取最后
		// 记录数
		$limitOffset = ($pageNo - 1) * $pageSize;
		// 获取直属下级用户数据
		$teamUserInfo = $this->field('id,uid,realname,at_time,state')->where($where)->order('at_time', 'desc')->limit($limitOffset, $pageSize)->select()->toArray();
		if (!count($teamUserInfo)) return ['code'=>0, 'code_dec'=>config($lang.'.lang')[45]];
		// 获取数据
		$data['data'] = model('UserDaily')->teamData($teamUserInfo);

		$data['code'] 				= 1;
		$data['data_total_nums'] 	= $count;
		$data['data_total_page'] 	= $pageTotal;
		$data['data_current_page'] 	= $pageNo;

		return $data;
	}

	//业绩报表
	public function userTeamrepost(){

		$param    =	input('param.');
		$userArr  =	explode(',',auth_code($param['token'],'DECODE'));
		$uid      =	$userArr[0];
		$lang	  = (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		// 搜索用户名
		$date = (isset($param['date']) && $param['date']) ?  strtotime($param['date']) : mktime(0, 0, 0, date('m'), date('d'), date('Y'));
		// 我的团队数据
		$myTeamData = model('UserDaily')->field(['SUM(`order`)'=>'order','SUM(`commission`)'=>'commission','SUM(`giveback`)'=>'giveback'])->join('user_team', 'ly_user_daily.uid = user_team.team')->where(array(['user_team.uid', '=', $uid],['user_team.team', '<>', $uid],['ly_user_daily.date', '=',$date]))->findOrEmpty();
		// 团队业绩
		$data['myself']['teamOrder']  = (isset($myTeamData['order'])) ? $myTeamData['order'] : 0;
		// 团队佣金
		$data['myself']['teamFee']    = (isset($myTeamData['commission'])) ? $myTeamData['commission'] : 0;
		// 团队收益
		$data['myself']['teamProfit'] = (isset($myTeamData['giveback'])) ? $myTeamData['giveback'] : 0;
		// 我的佣金
		$myFee = model('UserDaily')->field('commission,giveback')->where(array(['uid', '=', $uid],['date', '=',$date]))->findOrEmpty();
		// 我的佣金
		$data['myself']['myFee']           = (isset($myFee['commission'])) ? $myFee['commission'] : 0;
		// 我的收益
		$data['myself']['myProfit']        = (isset($myFee['giveback'])) ? $myFee['giveback'] : 0;
		// 所有下级佣金
		$data['myself']['teamFeeNotMe']    = $data['myself']['teamFee'] - $data['myself']['myFee'];
		// 所有下级收益
		$data['myself']['teamProfitNotMe'] = $data['myself']['teamProfit'] - $data['myself']['myProfit'];

		// 总记录数
		$count       = $this->where('sid', $uid)->count();
		if (!$count) return ['code'=>0, 'code_dec'=>config($lang.'.lang')[45]];
		// 每页显示记录
		$pageSize    = (isset($param['page_size']) and $param['page_size']) ? $param['page_size'] : 10;
		// 当前的页,还应该处理非数字的情况
		$pageNo      = (isset($param['page_no']) and $param['page_no']) ? $param['page_no'] : 1;
		// 总页数
		$pageTotal   = ceil($count / $pageSize);//当前页数大于最后页数，取最后
		// 记录数
		$limitOffset = ($pageNo - 1) * $pageSize;
		// 获取直属下级用户数据
		$teamUserInfo = $this->field('id,uid,realname')->where('sid', $uid)->order('id', 'asc')->limit($limitOffset, $pageSize)->select()->toArray();
		if(!count($teamUserInfo)){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[46]];
		}
		// 获取数据
		$data['data'] = model('UserDaily')->teamReport($date, $teamUserInfo);

		$data['code'] 				= 1;
		$data['data_total_nums'] 	= $count;
		$data['data_total_page'] 	= $pageTotal;
		$data['data_current_page'] 	= $pageNo;

		return $data;
	}


	//上级修改下级的费率
	public function setFee(){
		$param    =	input('param.');
		$userArr  =	explode(',',auth_code($param['token'],'DECODE'));
		$uid      =	$userArr[0];
		$lang	  = (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		// 判断是否是下级
		$is_x = $this->where(['id'=>$param['xid'],'sid'=>$uid])->count();
		if (!$is_x) return ['code'=>0, 'code_dec'=>config($lang.'.lang')[47]];

		// 获取用户自身费率
		$selfFee = $this->field('alipay_fee,wechat_fee,bank_fee')->where('id', $uid)->findOrEmpty();
		// 获取平台设置
		$setting = model('Setting')->field('u_alipay_fee_min,u_alipay_fee_max,u_wechat_fee_min,u_wechat_fee_max,u_bank_fee_min,u_bank_fee_max')->where('id','>',0)->findOrEmpty();

		$updateArray = array();
		/**
		 * 规则
		 */
		// 支付宝
		if (isset($param['alipay_fee']) && $param['alipay_fee']) {
			// 数据格式
			if (!is_numeric($param['alipay_fee'])) return ['code'=>0, 'code_dec'=>config($lang.'.lang')[48]];
			// 平台和上级
			if ($param['alipay_fee'] < $setting['u_alipay_fee_min'] || $param['alipay_fee'] > $selfFee['alipay_fee']) return ['code'=>0, 'code_dec'=>'支付宝费率应在'.$setting['u_alipay_fee_min'].' - '.$selfFee['alipay_fee'].'之间'];
			$updateArray['alipay_fee'] = $param['alipay_fee'];
		}
		// 微信
		if (isset($param['wechat_fee']) && $param['wechat_fee']) {
			// 数据格式
			if (!is_numeric($param['wechat_fee'])) return ['code'=>0, 'code_dec'=>'请填写有效的费率！'];
			// 平台和上级
			if ($param['wechat_fee'] < $setting['u_wechat_fee_min'] || $param['wechat_fee'] > $selfFee['wechat_fee']) return ['code'=>0, 'code_dec'=>'微信费率应在'.$setting['u_wechat_fee_min'].' - '.$selfFee['wechat_fee'].'之间'];
			$updateArray['wechat_fee'] = $param['wechat_fee'];
		}
		// 银行
		if (isset($param['bank_fee']) && $param['bank_fee']) {
			// 数据格式
			if (!is_numeric($param['bank_fee'])) return ['code'=>0, 'code_dec'=>'请填写有效的费率！'];
			// 平台和上级
			if ($param['bank_fee'] < $setting['u_bank_fee_min'] || $param['bank_fee'] > $selfFee['bank_fee']) return ['code'=>0, 'code_dec'=>'银行费率应在'.$setting['u_bank_fee_min'].' - '.$selfFee['bank_fee'].'之间'];
			$updateArray['bank_fee'] = $param['bank_fee'];
		}

		if (!$updateArray) return ['code'=>0, 'code_dec'=>config($lang.'.lang')[48]];

		$result = $this->where('id', $param['xid'])->update($updateArray);
		if (!$result) return ['code'=>0, 'code_dec'=>config($lang.'.lang')[49]];

		return ['code'=>1, 'code_dec'=>config($lang.'.lang')[50]];
	}


	//上级激活
	public function setactivationUser(){
		$param    =	input('param.');
		$userArr  =	explode(',',auth_code($param['token'],'DECODE'));
		$uid      =	$userArr[0];
		$xid	  = $param['xid'];//下级id
		$lang	  = (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		$xidinfo  =	$this->where('sid',$uid)->where('id',$xid)->count();//绑定银行卡数量
		if(!$xidinfo){
			$data['code'] = 0;
			$data['code_dec']	= '非直属下级,激活失败';
			return $data;
		}
		//激活
		$is = $this->where('sid',$uid)->where('id',$xid)->update(array('state'=>1,'at_time'=>time()));
		if(!$is){
			$data['code'] 		= 0;
			$data['code_dec']	= '激活失败';
			return $data;
		}
		$data['code'] 		= 1;
		$data['code_dec']	= '激活成功';
		return $data;
	}


	//私信
	public function msginfo(){

		$param    =	input('param.');
		$userArr  =	explode(',',auth_code($param['token'],'DECODE'));
		$uid      =	$userArr[0];
		$msgid	  = $param['msgid'];//下级id
		$lang	  = (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		$msginfo  = model('Message')->where(array(['id','=',$msgid],['uid','=',$uid],['state','=',2]))->find();
		if(!$msginfo){
			$data['code'] 		= 0;
			$data['code_dec']	= '无效私信';
			return $data;
		}

		//解锁 1
		$updatadata3 = array(
			'state'	=>	1,
		);
		model('Message')->where(array(['id','=',$msgid],['uid','=',$uid],['state','=',2]))->update($updatadata3);

		$data['code'] 		= 1;
		$data['content']	= $msginfo['content'];
		$data['add_time']	= date('Y-m-d H:i:s',$msginfo['add_time']);;
		$data['title']		= $msginfo['title'];
		return $data;
	}


	// 实名认证		(认证的实名必须与您绑定银行卡的开户名一致，否则将无法成功提现。)
	public function realname(){
		$param    	= input('param.');
		$userArr  	= explode(',',auth_code($param['token'],'DECODE'));
		$uid      	= $userArr[0];
		$realname		= input('post.realname/s');			// 真实姓名
		$identity_id	= input('post.identity_id/s');		// 身份证号
		$lang			= (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		if(!$realname || !$identity_id){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[53]];
		}

		// 获取用户信息
		$userinfo	= $this->where('id',$uid)->find();
		if(!$userinfo){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[2]];
		}

		if($userinfo['realname'] && $userinfo['identity_id']){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[54]];
		}

		$bank_username	= model('UserBank')->where('uid',$uid)->value('name');		// 获取用户银行卡持卡人姓名
		if(!$bank_username){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[185]];
		}

		if($bank_username != $realname){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[55]];
		}

		//正则身份证号
		$rule	= "/^[1-9]\d{5}(19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/i";	//正则规则
		if(!preg_match($rule, $identity_id)){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[56]];
		}

		$realname_data	= ['realname' => $realname, 'identity_id' => $identity_id];
		$is = $this->where('id',$uid)->update($realname_data);

		if($is){
			return ['code'=>1, 'code_dec'=>config($lang.'.lang')[57]];
		}
		return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
	}


	/**
		签到
	**/
	public function signin(){

		$param    	=	input('param.');
		$userArr  	=	explode(',',auth_code($param['token'],'DECODE'));
		$uid      	=	$userArr[0];
		$lang		= (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型
		$times		=	strtotime(date('Y-m-d',time()));
		$issignin	=	model('UserSignin')->where(array(['uid','=',$uid],['times','=',$times]))->count();
		if($issignin){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[58]];
		}

		$array = array(
			'uid'	=>	$uid,
			'times'	=>	$times
		);

		$in = model('UserSignin')->insertGetId($array);
		if($in){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[42]];
		}

		return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
	}

}
